//
//  YDPeripheralsViewController.m
//  IngCard
//
//  Created by kf on 2017/5/26.
//  Copyright © 2017年 IngDan. All rights reserved.
//

#import "YDPeripheralsViewController.h"
#import "YDPeripheralsTableViewCell.h"
#import "BabyBluetooth.h"
#import "YDCustomToastAnimator.h"
#import "YDCustomToastContentView.h"
#import "YDPeripheralDetailViewController.h"

@interface YDPeripheralsViewController ()
@property(nonatomic, strong) BabyBluetooth *baby;
@property(nonatomic, strong) NSMutableArray<CBPeripheral*> *peripherals;
@property(nonatomic, strong) QMUITips *tips;
@end

@implementation YDPeripheralsViewController

- (void) initDataSource
{
    [super initDataSource];
    
    [self initBabyDelegate];

    
    [self.baby cancelScan];
    [self.baby cancelAllPeripheralsConnection];
    self.baby.scanForPeripherals().begin().stop(10);
    self.tips = [QMUITips showLoading:@"正在查找设备" inView:self.tableView hideAfterDelay:2];
}

- (void) viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.baby cancelScan];
}

#pragma mark - private

-(void)initBabyDelegate{
    
    __weak __typeof(self)weakSelf = self;
    [self.baby setBlockOnCentralManagerDidUpdateState:^(CBCentralManager *central) {
        __strong __typeof(weakSelf)self = weakSelf;
    
        if (central.state != CBCentralManagerStatePoweredOn)
        {
            NSString *detailText = @"请上滑打开蓝牙！";
            
            QMUITips *tips = [QMUITips createTipsToView:self.tableView];
            tips.offset = CGPointMake(0, -40);
            tips.toastPosition = QMUIToastViewPositionBottom;
            YDCustomToastAnimator *customAnimator = [[YDCustomToastAnimator alloc] initWithToastView:tips];
            tips.toastAnimator = customAnimator;
            YDCustomToastContentView *customContentView = [[YDCustomToastContentView alloc] init];
            [customContentView renderWithImage:UIImageMake(@"ToastImage")
                                          text:@"小提示"
                                    detailText:detailText];
            tips.contentView = customContentView;
            [tips showAnimated:YES];
            [tips hideAnimated:YES afterDelay:3];
        }
        else if (central.state == CBCentralManagerStatePoweredOn)
        {
            [self initDataSource];
        }
    }];
    
    //设置扫描到设备的委托
    
    [self.baby setBlockOnDiscoverToPeripherals:^(CBCentralManager *central,
                                                 CBPeripheral *peripheral,
                                                 NSDictionary *advertisementData,
                                                 NSNumber *RSSI) {
        NSLog(@"搜索到了设备:%@",peripheral.name);
        __strong __typeof(weakSelf)self = weakSelf;
        
        [self.tips hideAnimated:NO];
        if (![self.peripherals containsObject:peripheral])
        {
            [self.peripherals addObject:peripheral];
            
            [self.dataSource addDataSource:[YDPeripheralsTableViewCellModel class]
                                    atSection:0
                                    config:^(YDPeripheralsTableViewCellModel* dataSource)
             {
                 dataSource.peripheral = peripheral;
                 dataSource.advertisementData = advertisementData;
                 dataSource.RSSI = RSSI;
             }];
        }
        
    }];
    
    //设置查找设备的过滤器
    [self.baby setFilterOnDiscoverPeripherals:^BOOL(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI) {
        if ([peripheralName hasPrefix:@"MT"] >0) {
            return YES;
        }
        return NO;
        
        return YES;
    }];
   
    [self.baby setBlockOnCancelScanBlock:^(CBCentralManager *centralManager) {
        
        Log(@"停止扫描");
    }];
}

#pragma mark - <UITableViewDelegate>
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //停止扫描
    [self.baby cancelScan];
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
   
    CBPeripheral *peripheral = self.peripherals[indexPath.row];// (CBPeripheral *)[self.dataSource dataSourceAtIndexPath:indexPath];
    
    [self.baby cancelScan];
    self.baby.having(peripheral).and.connectToPeripherals().discoverServices().discoverCharacteristics().
            readValueForCharacteristic().
            discoverDescriptorsForCharacteristic().
            readValueForDescriptors().begin();

    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}


#pragma mark - lazy loading

- (BabyBluetooth *)baby
{
    if (!_baby)
    {
        _baby = [BabyBluetooth shareBabyBluetooth];
        NSDictionary *scanForPeripheralsWithOptions = @{CBCentralManagerScanOptionAllowDuplicatesKey:@YES};
        [_baby setBabyOptionsWithScanForPeripheralsWithOptions:scanForPeripheralsWithOptions
                                  connectPeripheralWithOptions:nil
                                scanForPeripheralsWithServices:nil
                                          discoverWithServices:nil
                                   discoverWithCharacteristics:nil];
    }
    return _baby;
}

-(NSMutableArray<CBPeripheral*> *)peripherals
{
    if(!_peripherals)
    {
        _peripherals = [NSMutableArray array];
    }
    return _peripherals;
}

@end
